package Meituan;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 测试compare方法
 * @author: leiwenkang02@meituan.com
 * @date: 2018/4/21
 * @time: 11:41
 */
public class Test02 {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student student1 = new Student(1, "zhangsan", 18);
        Student student2 = new Student(2, "lisi", 58);
        Student student3 = new Student(3, "wangwu", 38);
        Student student4 = new Student(4, "zhangliu", 28);
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);

        //方法1：构造比较器，  该方法默认是以从小到大顺序排序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge();//表示age越大，student越大
//                return o2.getAge() - o1.getAge();//表示age越小，student越大
            }
        });



        //方法2 : 实现comparable接口，实现compareTo接口
//        Collections.sort(list);

        list.forEach(student -> {
            System.out.println(student.toString());
        });
    }
}



class Student implements Comparable {

    private int id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        return this.getAge() - ((Student) o).getAge();
    }
}
